﻿/*
 Author:du
 Time:2017.12.11
*/

using UnityEngine;
using UnityEditor;
using FutureCoreEditor;
using System.IO;

public class AutoTextureImportTool : AssetPostprocessor
{
    private TextureImporter importer;
    private string jpgExtension = ".jpg";
    private string pngExtension = ".png";
    private string uiAtlasName = "UI_";
    private string framesAtlasName = "Frames_";
    private string effectAtlasName = "Effect_";

    void OnPreprocessTexture()
    {
        importer = (TextureImporter)assetImporter;

        if (assetPath.IndexOf("_Game/ResourcesArt/Atlas") != -1)
        {
            UniformSet();
            DoSettings(true, false);
            SetSpriteMeshType(false);
            importer.textureType = TextureImporterType.Sprite;
            importer.spriteImportMode = SpriteImportMode.Single;
            string dirName = Path.GetDirectoryName(assetPath);
            string spritePackingTag = Path.GetFileName(dirName);
            importer.spritePackingTag = GEditorTool.AtlasTP_RECT + uiAtlasName + spritePackingTag;
            SetAlphaIsTransparency(true);
        }
        else if (assetPath.IndexOf("_Game/ResourcesArt/Frames") != -1)
        {
            UniformSet();
            DoSettings(true, false);
            SetSpriteMeshType(true);
            importer.textureType = TextureImporterType.Sprite;
            importer.spriteImportMode = SpriteImportMode.Single;
            string folderName = "Frames";
            string spritePackingTag = assetPath.Substring(assetPath.IndexOf(folderName) + folderName.Length + 1);
            spritePackingTag = spritePackingTag.Substring(0, spritePackingTag.IndexOf("/"));
            importer.spritePackingTag = GEditorTool.AtlasTP_TIGHT + framesAtlasName + spritePackingTag;
            SetAlphaIsTransparency(true);
        }
        else if (assetPath.IndexOf("_Game/ResourcesArt/Sprite") != -1)
        {
            UniformSet();
            DoSettings(false, true);
            SetSpriteMeshType(false);
            importer.textureType = TextureImporterType.Sprite;
            importer.spriteImportMode = SpriteImportMode.Single;
            importer.spritePackingTag = null;
            SetAlphaIsTransparency(true);
            SetSingleSpriteFormat(assetPath);
        }
        else if (assetPath.IndexOf("_Game/Resources/Texture") != -1)
        {
            UniformSet();
            DoSettings(false, false, false);
            importer.textureType = TextureImporterType.Default;
            importer.textureShape = TextureImporterShape.Texture2D;
            SetAlphaIsTransparency(false);
        }
        else if (assetPath.IndexOf("_Game/ResourcesArt/EffectLib") != -1 && assetPath.IndexOf("FE") != -1)
        {
            UniformSet();
            importer.textureType = TextureImporterType.Sprite;
            importer.spriteImportMode = SpriteImportMode.Single;
            DirectoryInfo dir = new DirectoryInfo(assetPath);
            int fileNum = dir.Parent.GetFiles().Length;
            if (fileNum > 2)
            {
                DoSettings(true, false);
                SetSpriteMeshType(true);
                string folderName = "EffectLib";
                string spritePackingTag = assetPath.Substring(assetPath.IndexOf(folderName) + folderName.Length + 1);
                spritePackingTag = spritePackingTag.Substring(0, spritePackingTag.IndexOf("/"));
                importer.spritePackingTag = GEditorTool.AtlasTP_TIGHT + effectAtlasName + spritePackingTag;
            }
            else
            {
                DoSettings(false, true);
                SetSpriteMeshType(false);
                SetSingleSpriteFormat(assetPath);
                importer.spritePackingTag = null;
            }
            SetAlphaIsTransparency(true);
        }
        else if (assetPath.IndexOf("_Game/ResourcesArt/EffectLib") != -1)
        {
            UniformSet();
            DoSettings(false, false, true);
            importer.textureType = TextureImporterType.Default;
            importer.textureShape = TextureImporterShape.Texture2D;
            SetAlphaIsTransparency(false);
        }
        else if (assetPath.IndexOf("_Game/ResourcesArt/Skeleton") != -1)
        {
            UniformSet();
            DoSettings(false, false, true);
            importer.textureType = TextureImporterType.Default;
            importer.textureShape = TextureImporterShape.Texture2D;
            SetAlphaIsTransparency(false);
        }
    }

    private void UniformSet()
    {
        importer.ClearPlatformTextureSettings("Android");
        importer.ClearPlatformTextureSettings("iPhone");
        importer.ClearPlatformTextureSettings("Standalone");

        importer.spritePixelsPerUnit = EPAppConst.PixelsPerUnit;
        importer.mipmapEnabled = false;
        importer.isReadable = false;
        importer.sRGBTexture = true;
        importer.wrapMode = TextureWrapMode.Clamp;
        importer.filterMode = FilterMode.Bilinear;
        importer.alphaSource = TextureImporterAlphaSource.FromInput;
    }

    private void DoSettings(bool isAtlas, bool isSingleSprite, bool isTextureAlpha = false)
    {
        int maxSize = GetMaxTextureSize();

        TextureImporterPlatformSettings defaultSetting = importer.GetDefaultPlatformTextureSettings();
        defaultSetting.maxTextureSize = maxSize;
        defaultSetting.textureCompression = TextureImporterCompression.Compressed;
        defaultSetting.compressionQuality = (int)TextureCompressionQuality.Normal;
        importer.SetPlatformTextureSettings(defaultSetting);

        TextureImporterPlatformSettings standaloneSetting = importer.GetPlatformTextureSettings("Standalone");
        standaloneSetting.overridden = true;
        standaloneSetting.maxTextureSize = maxSize;
        standaloneSetting.textureCompression = TextureImporterCompression.Compressed;
        standaloneSetting.format = TextureImporterFormat.DXT5Crunched;
        importer.SetPlatformTextureSettings(standaloneSetting);

        TextureImporterPlatformSettings androidSetting = importer.GetPlatformTextureSettings("Android");
        androidSetting.overridden = true;
        androidSetting.maxTextureSize = maxSize;
        androidSetting.textureCompression = TextureImporterCompression.Compressed;
        SetTextureFormat(androidSetting, isAtlas, isSingleSprite, isTextureAlpha);
        importer.SetPlatformTextureSettings(androidSetting);

        TextureImporterPlatformSettings iPhoneSetting = importer.GetPlatformTextureSettings("iPhone");
        iPhoneSetting.overridden = true;
        iPhoneSetting.maxTextureSize = maxSize;
        iPhoneSetting.textureCompression = TextureImporterCompression.Compressed;
        iPhoneSetting.format = TextureImporterFormat.ASTC_RGBA_4x4;
        importer.SetPlatformTextureSettings(iPhoneSetting);
    }

    private void SetSpriteMeshType(bool isTight)
    {
        TextureImporterSettings setting = new TextureImporterSettings();
        importer.ReadTextureSettings(setting);
        if (isTight)
        {
            setting.spriteMeshType = SpriteMeshType.Tight;
        }
        else
        {
            setting.spriteMeshType = SpriteMeshType.FullRect;
        }
        importer.SetTextureSettings(setting);
    }

    private void SetTextureFormat(TextureImporterPlatformSettings androidSetting, bool isAtlas, bool isSingleSprite, bool isTextureAlpha)
    {
        if (isAtlas)
        {
            androidSetting.allowsAlphaSplitting = true;
            androidSetting.format = TextureImporterFormat.ETC_RGB4;
        }
        else if (isSingleSprite)
        {
            androidSetting.allowsAlphaSplitting = false;
            androidSetting.format = TextureImporterFormat.RGB16;
        }
        else if (isTextureAlpha)
        {
            androidSetting.allowsAlphaSplitting = false;
            androidSetting.format = TextureImporterFormat.ETC2_RGBA8;
        }
        else
        {
            androidSetting.allowsAlphaSplitting = false;
            androidSetting.format = TextureImporterFormat.ETC2_RGB4;
        }
    }

    private void SetSingleSpriteFormat(string assetPath)
    {
        string fileExtension = Path.GetExtension(assetPath);
        TextureImporterPlatformSettings androidSetting = importer.GetPlatformTextureSettings("Android");
        if (fileExtension.Equals(jpgExtension))
        {
            androidSetting.format = TextureImporterFormat.RGB16;
            importer.alphaIsTransparency = false;
        }
        else if (fileExtension.Equals(pngExtension))
        {
            androidSetting.format = TextureImporterFormat.RGBA16;
            importer.alphaIsTransparency = true;
        }
        importer.SetPlatformTextureSettings(androidSetting);
    }

    private int GetMaxTextureSize()
    {
        int textureSize = 2048;
        Texture texture = AssetDatabase.LoadAssetAtPath<Texture>(importer.assetPath);
        if (texture != null)
        {
            textureSize = Mathf.Max(texture.width, texture.height);
            textureSize = GetMaxSize(textureSize);
        }
        else
        {
            Debug.Log("外部首次导入需要ReImport: " + importer.assetPath);
        }
        return textureSize;
    }

    private int GetMaxSize(int size)
    {
        int maxSize = 8192;
        while (true)
        {
            if (maxSize < 32)
            {
                return 32;
            }
            if (size > maxSize)
            {
                if (maxSize * 2 > 8192)
                {
                    return 8192;
                }
                return maxSize * 2;
            }
            maxSize = maxSize / 2;
        }
    }

    private void SetAlphaIsTransparency(bool isTransparency)
    {
        importer.alphaIsTransparency = isTransparency;
    }
}